/************************************************
 * Copyright (c) 2007 ~ 2009, 
 * All rights reserved.
 * Version   : 1.0
 * Author    : lengsh@gmail.com 
 * Date      : 2009.1.2
 ************************************************/

#ifndef  __MEMCACHE_CONNECTION__H__
#define  __MEMCACHE_CONNECTION__H__

#include <libmemcached/memcached.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <string>
#include <iostream>
#include <glib.h>
#include "define.h"

using namespace std;

/*
#define MCONN_MC_DOWN    -1 
#define MCONN_MC_OK       0
#define MCONN_MC_FAIL     1
#define MCONN_MC_RESTART  2
#define MCONN_MC_NEXT     3
#define MCONN_MC_LIVE     0 
#define MCONN_MC_NULL     4
*/

/*
 *
 */
#define DEAD_CHECK_TIME       600

namespace panda {
class MemConnection
{
	protected:
		memcached_st * m_pMemc;
                string get_localhost_ip(char *eth);
	public:
		long m_lLasttime;
                long m_lCurtime;
		bool m_bLive;
		int m_iKey;
		string m_sHostname;
		string m_sHostIP;
		int m_iPort;
		int m_iBackup;
		int getStatus();
		long getLastTime(){ return m_lLasttime; }
                long getCurrTime(){ return m_lCurtime;  }
		MemConnection(const char *hname, int port, int ik, int ib ):
			m_sHostname(hname), m_iPort(port), m_iBackup(ib)
	{
		m_iKey = ik;
		m_lLasttime = 0;
		m_bLive = false;
		m_pMemc = NULL;
	}
		~MemConnection(){   disConnect();        }
		bool Connect();
		int Set(const char *k, unsigned int klen, const char *v, unsigned vlen, long expire = 0);
		int Delete(const char *k, unsigned int klen) ;

		int Get( const char *data, unsigned int dlen, const char *prefix, char **wbuf,unsigned &wsize, unsigned &wbytes);
		int MGet( const char *data, unsigned int dlen, int argc, const char *prefix, char **wbuf, unsigned &wsize, unsigned &wbytes);
		int Incr(const char *data, unsigned dlen, const char *prefix, char **wbuf,unsigned &wsize,  unsigned &wbytes);
		int Decr(const char *data, unsigned dlen, const char *prefix, char **wbuf,unsigned &wsize, unsigned &wbytes);

		void Print();
	private:
		void disConnect();
};

}
#endif  // __MEMCACHE_CONNECTION__H__
